﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using FileManager_Client.BusinessLogic;
using FileManager_Client.BusinessLogic.FileManagerUserService;
using FileManager_Client.Utility;

namespace FileManager_Client.PresentationLayer.NewUi
{
    public partial class ReNameFileForm : BaseForm
    {
        #region Form Constructor
        private UserLoginResult userSession;
        private List<string> _hasFileNameCollection;
        private string _fileSid;
        private string _fileOldName;
        private FileService fileService;
        private LoadingWaitForm _loadingWaitForm;
        private string _folderId;
        private FileManager_Form _fileManagerForm;
        private static object lockWait = new object();
        public ReNameFileForm(List<string> hasFileNameCollection, string fileSid, string fileOldName, string folderId, FileManager_Form fileManagerForm)
        {
            InitializeComponent();
            _hasFileNameCollection = hasFileNameCollection;
            _fileSid = fileSid;
            _fileOldName = fileOldName;
            userSession = CacheGlobal.GetCache(GlobalString.System_Config_String.UserSession) as UserLoginResult;
            Tb_FileName.TextChanged += Tb_FileName_TextChanged;
            Tb_FileName.KeyPress += Tb_FileName_KeyPress;
            fileService = new FileService();
            _folderId = folderId;
            _fileManagerForm = fileManagerForm;
            Tb_FileName.Text = fileOldName;
            Ttc_Message.ShowShadow = true;
            Ttc_Message.Rounded = true;
            Ttc_Message.ShowBeak = true;
            Ttc_Message.SetToolTipIconType(Tb_FileName, ToolTipIconType.Information);
        }
        #endregion

        #region Txtbox FileRename Event
        void Tb_FileName_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 13) return;
            if (CheckFileName())
                FileReName();
        }

        void Tb_FileName_TextChanged(object sender, EventArgs e)
        {
            Ttc_Message.HideHint();
        }
        #endregion

        #region Button Confirm Event
        private void Btn_Confirm_Click(object sender, EventArgs e)
        {
            if (CheckFileName())
                FileReName();
        }
        #endregion

        #region File Rename Method
        private void FileReName()
        {
            try
            {
                lock (lockWait)
                {
                    _loadingWaitForm = new LoadingWaitForm();
                    _loadingWaitForm.SetCaption(GlobalString.System_Config_String.MbxInfoStr);
                    _loadingWaitForm.SetDescription(GlobalString.System_Config_String.FileReNameStr);
                }
                var backgroundWorker = new BackgroundWorker();
                backgroundWorker.DoWork += backgroundWorker_DoWork;
                var fileReNameArgs = new FileReNameArgs
                {
                    FileNewNamek__BackingField = Tb_FileName.Text,
                    FileSidk__BackingField = _fileSid,
                    UserIdk__BackingField = userSession.UserIdk__BackingField
                };
                backgroundWorker.RunWorkerAsync(fileReNameArgs);
                _loadingWaitForm.ShowDialog();
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("FileReName has problem", ex);
                XtraMessageBox.Show("修改文件名失败!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
            }
        }

        void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                var fileArgs = e.Argument as FileReNameArgs;
                var reslut = fileService.ChangeFileName(fileArgs);
                Invoke((EventHandler)delegate
                {
                    _loadingWaitForm.Close();
                });
                if (reslut.Resultk__BackingField)
                {
                    XtraMessageBox.Show("修改文件名成功!", GlobalString.System_Config_String.MbxInfoStr,
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                    _fileManagerForm.Invoke((EventHandler)delegate
                    {
                        _fileManagerForm.UpdateListView(_folderId);
                    });
                    Invoke((EventHandler)delegate
                    {
                        Close();
                    });
                }
                else
                {
                    var message = string.Empty;
                    switch (reslut.ResultExceptionk__BackingField)
                    {
                        case BaseExceptionEnum.NotFindFileException:
                            message = GlobalString.System_Exception_String.NotFindFileExceptionStr;
                            break;
                        case BaseExceptionEnum.FileReNameException:
                            message = GlobalString.System_Exception_String.FileReNameExceptionStr;
                            break;
                        case BaseExceptionEnum.FileUploading:
                            message = GlobalString.System_Exception_String.FileUploadingExceptionStr;
                            break;
                    }
                    XtraMessageBox.Show(message, GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("FileReName backgroundWorker_DoWork has problem", ex);
                XtraMessageBox.Show("修改文件名失败!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                Invoke((EventHandler)delegate
                {
                    Close();
                });
            }
        }
        #endregion

        #region Check File Name Method
        private bool CheckFileName()
        {
            var fileName = Tb_FileName.Text;
            if (fileName.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) != -1)
            {
                ShowTipMessage("文件名不能包含\\/:*?\"<>| 特殊字符!");
                return false;
            }
            if (string.IsNullOrEmpty(fileName.Trim()) || fileName.Substring(fileName.LastIndexOf('.')).Equals(fileName))
            {
                ShowTipMessage("文件名不能为空!");
                return false;
            }
            if (_fileOldName.Equals(fileName))
            {
                ShowTipMessage("文件名没有发生变化!");
                return false;
            }
            if (_hasFileNameCollection.Contains(fileName))
            {
                ShowTipMessage("该文件夹中已经包含了这个文件名!");
                return false;
            }
            return true;
        }

        private void ShowTipMessage(string message)
        {
            Ttc_Message.ShowHint(message, Tb_FileName, ToolTipLocation.BottomCenter);
        }
        #endregion
    }
}